package org.finesys.common.hazelcast.core.support;

import com.hazelcast.config.Config;
import com.hazelcast.config.NetworkConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import org.springframework.beans.factory.DisposableBean;

import java.util.Arrays;
import java.util.List;
import java.util.StringJoiner;


/**
 * HazelcastClientFactory 用于创建 Hazelcast节点实例
 */
public class HazelcastServerInstance implements DisposableBean {

    private final HazelcastProperties hazelcastProperties;
    private HazelcastInstance hazelcastInstance;

    public HazelcastServerInstance(HazelcastProperties hazelcastProperties) {
        this.hazelcastProperties = hazelcastProperties;
        //配置实例名称
        Config config = new Config(hazelcastProperties.getInstanceName());
        //配置集群名称
        config.setClusterName(hazelcastProperties.getClusterName());
        //配置网络
        configNetWork(config.getNetworkConfig());
        //创建实例
        hazelcastInstance = Hazelcast.newHazelcastInstance(config);
    }

    private void configNetWork(NetworkConfig networkConfig) {
        //实例端口配置，端口自增
        networkConfig.setPort(hazelcastProperties.getPort().get(0)).setPortAutoIncrement(true);
        // 禁用AWS云，使用TCP/IP协议进行成员发现和通信
        networkConfig.getJoin().getAwsConfig().setEnabled(false);
        // 禁止多播，Hazelcast集群节点将无法自动加入到集群中
        networkConfig.getJoin().getMulticastConfig().setEnabled(false);
        // 启用TCP/IP协议，通过指定节点地址信息，Hazelcast节点将通过TCP/IP协议加入到集群中
        networkConfig.getJoin().getTcpIpConfig().setEnabled(true).setMembers(members()).setRequiredMember(null);

    }

    private List<String> members() {
        StringJoiner joiner = new StringJoiner(",");
        hazelcastProperties.getMembers().stream().flatMap(m -> hazelcastProperties.getPort().stream().map(p -> m + ":" + p))
                .forEach(joiner::add);
        return Arrays.asList(joiner.toString().split(","));
    }

    @Override
    public void destroy() {
        hazelcastInstance.shutdown();
    }
}
